package com.ktjiaoyu.service.impl;

import com.ktjiaoyu.service.UploadService;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service("toLocalUploadService")
public class ToLocalUploadServiceImpl implements UploadService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ToLocalUploadServiceImpl.class);
    /*
    上传文件的保存目录
     */
    public static final String UPLOAD_PATH = "/statics/upload/";
    @Autowired
    private HttpServletRequest request;  //注入request对象 主要是为了获取本地路径

    @Override
    public String uploadFile(MultipartFile uploadFile, String... allowFileExtends) throws Exception {
        Set<String> include = new HashSet<>(Arrays.asList(allowFileExtends)); //将数组转换为set集合
        //获取保存路径 将Web应用中的相对路径转换为服务器文件系统上的绝对路径
        String rootPath = request.getServletContext().getRealPath(UPLOAD_PATH);
        //如果文件非空说明上传了文件数据
        if (!uploadFile.isEmpty()) {
            String fileName = uploadFile.getOriginalFilename(); //获取上传文件的原始名称
            //获得上传文件的扩展名
            String extension = StringUtils.getFilenameExtension(fileName);
            if (!include.contains(extension)) {
                throw new RuntimeException("上传的文件类型不合法,仅支持" + include + "类型的文件");
            }
            String uploadFileName = UUID.randomUUID() + "." + extension; //生成新的文件名
            File file = new File(rootPath + uploadFileName);  //文件的保存路径
            //父目录不存在是无法保存的
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            try {
                //将上传的文件保存到本地路径
                uploadFile.transferTo(file);
                //返回访问路径
                return UPLOAD_PATH + uploadFileName;
            } catch (Exception e) {
                LOGGER.error("执行ToLocalUploadServiceImpl.uploadFile(MultipartFile String[])上传文件异常", e);
                throw e;
            }
        }
        return null;
    }
}
